<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="员工" prop="userId">
        <UserSelect @node-change="handleUserChange" v-model="formData.userId" />
      </el-form-item>
      <el-form-item label="年份" prop="years">
        <el-date-picker
          v-model="formData.years"
          value-format="YYYY"
          type="year"
          placeholder="选择年份"
        />
      </el-form-item>
      <el-form-item label="基本工资" prop="baseSalary">
        <el-input v-model="formData.baseSalary" placeholder="请输入基本工资" />
      </el-form-item>
      <el-form-item label="岗位工资" prop="positionSalary">
        <el-input v-model="formData.positionSalary" placeholder="请输入岗位工资" />
      </el-form-item>
      <el-form-item label="试用期工资" prop="probationSalary">
        <el-input v-model="formData.probationSalary" placeholder="请输入试用期工资" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入备注" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="handleBatchGenerate"
        v-hasPermi="['oa:employee-archive:generate-salary-standard']"
        style="margin-bottom: 16px;"
      >
        批量生成
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SalaryStandardApi, SalaryStandardVO } from '@/api/oa/salarystandard'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { EmployeeArchiveApi } from '@/api/oa/employeearchive'
import { useMessage } from '@/hooks/web/useMessage'

/** 工资标准管理 表单 */
defineOptions({ name: 'SalaryStandardForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined as number | undefined,
  userName: undefined as string | undefined,
  years: undefined as string | undefined,
  baseSalary: undefined,
  positionSalary: undefined,
  probationSalary: undefined,
  remarks: undefined,
  hireDate: undefined as string | undefined,
  endDate: undefined as string | undefined,
})
const formRules = reactive({
  userId: [{ required: true, message: '员工不能为空', trigger: 'change' }],
  years: [{ required: true, message: '年份不能为空', trigger: 'change' }],
  baseSalary: [{ required: true, message: '基本工资不能为空', trigger: 'blur' }],
  positionSalary: [{ required: true, message: '岗位工资不能为空', trigger: 'blur' }],
  probationSalary: [{ required: true, message: '试用期工资不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const handleUserChange = (row: any) => {
  formData.value.userId = row.id
  formData.value.userName = row.nickName
}

/** 打开弹窗 */
const open = async (type: string, id?: number, userId?: number, userName?: string, years?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 新增时自动带入 userId、userName、years
  if (type === 'create') {
    if (userId) formData.value.userId = userId
    if (years) formData.value.years = String(years)
    if ('userName' in formData.value && userName) formData.value.userName = userName
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await SalaryStandardApi.getSalaryStandard(id)
      formData.value = { ...formData.value, ...res, years: res.years ? String(res.years) : undefined }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SalaryStandardVO
    if (formType.value === 'create') {
      await SalaryStandardApi.createSalaryStandard(data)
      message.success(t('common.createSuccess'))
    } else {
      await SalaryStandardApi.updateSalaryStandard(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined as number | undefined,
    userName: undefined as string | undefined,
    years: undefined as string | undefined,
    baseSalary: undefined,
    positionSalary: undefined,
    probationSalary: undefined,
    remarks: undefined,
    hireDate: undefined as string | undefined,
    endDate: undefined as string | undefined,
  }
  formRef.value?.resetFields()
}

const handleBatchGenerate = async () => {
  if (!formData.value.userId || !formData.value.userName || !formData.value.hireDate || !formData.value.baseSalary) {
    message.error('请先填写完整的员工信息')
    return
  }
  await EmployeeArchiveApi.generateSalaryStandard({
    userId: formData.value.userId,
    userName: formData.value.userName,
    hireDate: formData.value.hireDate,
    endDate: formData.value.endDate,
    salary: String(formData.value.baseSalary),
  })
  message.success('批量生成成功')
  // 重新加载工资标准列表
  if (typeof loadSalaryStandardList === 'function') {
    loadSalaryStandardList()
  }
}
</script>